package com.schoolcloud.front.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolcloud.common.exception.LoginUserException;
import com.schoolcloud.common.exception.UserNotExistException;
import com.schoolcloud.common.model.FrontUserLoginDTO;
import com.schoolcloud.common.model.PageDTO;
import com.schoolcloud.common.model.UserInfo;
import com.schoolcloud.common.util.UserContext;
import com.schoolcloud.front.entity.FroUser;
import com.schoolcloud.front.mapper.FroUserMapper;
import com.schoolcloud.front.query.FroUserQuery;
import com.schoolcloud.front.service.FroUserService;
import com.schoolcloud.front.service.UserFollowService;
import com.schoolcolud.daomybatisplus.dto.MpPageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author hongmizfb
 * @description 针对表【fro_user】的数据库操作Service实现
 * @createDate 2025-02-09 09:55:50
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class FroUserServiceImpl extends ServiceImpl<FroUserMapper, FroUser>
        implements FroUserService {
    private final UserFollowService userFollowService;

    @Override
    public PageDTO<FroUser> getUserQuery(FroUserQuery query) {
        String keywords = query.getKeywords();
        Page<FroUser> page = lambdaQuery().eq(StrUtil.isNotBlank(keywords), FroUser::getUserId, keywords)
                .page(query.toMpPage());
        return MpPageUtil.of(page, FroUser.class);
    }

    @Override
    public FroUser login(FrontUserLoginDTO froUser) {
        String account = froUser.getAccount();
        String password = froUser.getPassword();
        FroUser one = lambdaQuery().eq(StrUtil.isNotBlank(account), FroUser::getPhone, account)
                .or().eq(StrUtil.isNotBlank(account), FroUser::getUserName, account)
                .or().eq(StrUtil.isNotBlank(account), FroUser::getUserId, account)
                .one();
        if (one == null || !one.getPassword().equals(password)) {
            log.error("用户名或密码输入错误");
            throw new LoginUserException("用户名或密码输入错误");
        }
        return one;
    }

    @Override
    public UserInfo getUserInfo(Integer userToInteger) {
        FroUser byId = getById(userToInteger);
        UserInfo froUserInfo = new UserInfo();
        BeanUtils.copyProperties(byId, froUserInfo);
        try {
            Integer loginUserId = UserContext.getUserToInteger();
            if (!byId.getUserId().equals(loginUserId)) {
                Boolean aBoolean = userFollowService.chexkIsFollow(froUserInfo.getUserId());
                froUserInfo.setIsFollow(aBoolean);
            }
        }
        catch (Exception e){
            e.printStackTrace();
            log.info("没有登陆，无法判断当前用户是否关注");
        }

        return froUserInfo;
    }
}




